<?php
/*
 * Created on 31 mars 07
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */

 /* SQL update
  * ALTER TABLE `comments` CHANGE `post_id` `page_id` INT( 10 ) NOT NULL 
  * */
  
 uses('sanitize');

 class Comment extends appModel{
 	var $name = 'Comment';
 	
 	var $validate = array(
 					'content' => VALID_NOT_EMPTY,
 					'author' => VALID_NOT_EMPTY,
 					'email' => VALID_EMAIL
 					);
 	
 	var $belongsTo = array('Page' => array(
 									'className' => 'Page',
 									'conditions' => '',
 									'order' => '',
 									'foreignKey' => 'page_id'
 									)
 								);
 	
 	function validates(){
		/*	^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*$	*/
 		/* 	 (http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])? */
 		/* '`((https?)://\S+[[:alnum:]]/?)`si'  */
 		
 		if(!empty($this->data['Comment']['website'])){
 			if(!preg_match('`^(https?://)([[:alnum:]-\.]+)\.[[:alpha:]]{2,4}(/?[[:alnum:]-\._\+\?&~%;]+)*$`', $this->data['Comment']['website'])){
 				$this->invalidate('website');
 				//$this->set('website_error', 'Seems it\'s not a valid url.');
 			}
		}else{
			unset($this->data['Comment']['website']);
		}
		
		//This prevent from spam : allow only $maxlink http : href and render
		$maxlink = 6;
		$count = preg_match_all('(http://)', $this->data['Comment']['content'], $out);
		if($count > $maxlink){
			$this->invalidate('content');
			$this->set('website_error', 'Spam Prevent');
			
			//LOG: Spaming attempt
		}
		
		
        return count($this->invalidFields()) == 0;
	}
							
 	function beforeSave(){
 		
 		$san = new Sanitize();
		$this->data['Comment']['author'] = $san->paranoid($this->data['Comment']['author'], array('.', '-', '+', ':', ' '));
		$this->data['Comment']['email'] = $san->paranoid($this->data['Comment']['email'], array('@', '.', '-', '+'));
		//$this->data['Comment']['website'] = $san->paranoid($this->data['Comment']['website'], array('.', '-', '+', '/', ':'));
		//$this->data['Comment']['content'] = $san->sql($this->data['Comment']['content']); //cake 1.2 : removed
		$this->data['Comment']['content'] = $san->stripAll($this->data['Comment']['content']);
		return true;
	}
 	
 	function afterSave(){
 		$comments_count = $this->findCount(array('page_id' => $this->data['Comment']['page_id']));
 		
 		$this->Page->id = $this->data['Comment']['page_id'];
 		$this->Page->saveField('comments_count', $comments_count);
	}
 	
 }
?>
